<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0, user-scalable=no">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
</head>
  <body>
      <div id="app">观察者模式</div>
      <script>
          // 发布者- 目标- Dep
          class Dep {
            constructor () {
                // 记录所有的订阅者
                this.subs = []
            }
            // 添加订阅者
            addSub (sub) {
                // 判断订阅者是否存在并具有update方法
                if(sub && sub.update) {
                    this.subs.push(sub)
                }
            }
            // 发布订阅
            notify () {
                this.subs.forEach(sub => {
                    sub.update()
                })
            }
          }
          // 订阅者- 观察- Watcher
          class Watcher {
            // 更新视图
            update () {
                console.log('update')
            }
          }

        // 测试
        let dep = new Dep()
        let watcher = new Watcher()
        dep.addSub(watcher)
        dep.notify()

      </script>
  </body>
</html>